package leetcode.code1592;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public String reorderSpaces(String text) {
		char[] cs = text.toCharArray();
		int bc = 0, wc = 0, len = cs.length;
		for (int i = 0; i < len; i++) {
			char c = cs[i];
			if (c == ' ') {
				bc++;
				if (i - 1 >= 0) {
					if (cs[i - 1] != ' ') {
						wc++;
					}
				}
			}
		}
		if (cs[len - 1] != ' ') {
			wc++;
		}
		int avg = wc == 1 ? bc : bc / (wc - 1);
		StringBuffer sb = new StringBuffer();
		int p = 0;
		while (p < len) {
			char c = cs[p];
			if (c != ' ') {
				sb.append(c);
				p++;
			} else {
				if (sb.length() > 0) {
					int range = Math.min(bc, avg);
					for (int i = 0; i < range; i++) {
						sb.append(' ');
					}
					bc -= range;
				}
				while (p < len && cs[p] == ' ') {
					p++;
				}
			}
		}
		if (bc > 0) {
			for (int i = 0; i < bc; i++) {
				sb.append(' ');
			}
		}
		return sb.toString();
	}

	@Override
	public void debug4() {
		HelpDebug.compare("a b c d  ", this.reorderSpaces("a b   c d"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
